package com.example.onlinemarket.controller;

import com.example.onlinemarket.bean.*;
import com.example.onlinemarket.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
@RequestMapping("/shop")
public class ShopController {
    private UserService userService;
    private GoodService goodService;
    private OrderService orderService;
    private OrderItemService orderItemService;
    @Autowired
    public void setOrderItemService(OrderItemService orderItemService) { this.orderItemService = orderItemService; }
    @Autowired
    public void setOrderService(OrderService orderService) { this.orderService = orderService; }
    @Autowired
    public void setUserService(UserService userService){
        this.userService = userService;
    }
    @Autowired
    public void setGoodService(GoodService goodService){
        this.goodService = goodService;
    }

    private Logger logger;
    @Autowired
    public void setLogger(){ this.logger = LoggerFactory.getLogger(ShopController.class);
    }

    //更新订单状态
    @RequestMapping("/updateStatus")
    public String updateStatus(HttpSession session, String goodStatus, Integer orderId, Integer userId){
        User loginUser = (User) session.getAttribute("loginUser");
        if(loginUser.isRole()){//必须为卖家操作
            if(loginUser.getUserId().equals(userId)) {
                //若goodStatus包含"退款中"字样则取分隔线前的字段
                if(goodStatus.contains("退款中")){
                    goodStatus = goodStatus.split("-")[0];
                }
                //更新订单状态
                boolean flag1 = orderItemService.updateShopGoodStatus(userId, orderId, goodStatus);
                boolean flag2 = orderService.updateOrderStatus(orderId, goodStatus, loginUser.getAddress());
                boolean flag3;
                if(goodStatus.equals("已发货")) {
                    flag3 = true;
                }else{
                    flag3 = goodService.updateSellNumAndQuantity(orderId, false);
                }
                if (flag1||flag2||flag3){
                    System.out.println("操作完成");
                    switch (goodStatus){//
                        case "已发货":
                            goodStatus = "sent";
                            break;
                        case "待发货":
                            goodStatus = "unsent";
                            break;
                        case "已退款":
                            goodStatus = "refunding";
                            break;
                    }
                    return "pages/shop/shopOrder/"+goodStatus;
                }else{//若操作失败则事务回滚
                    // TODO: 2021/1/11 事务回滚
                    System.out.println("操作失败，系统出现错误，请稍候重试！");
                    return "pages/shop/shopIndex";
                }
            }else{//若不是本人操作则返回
                // TODO: 2021/1/11  非法操作11
                System.out.println("非法操作12，不能操作其他商家的订单");
                return "pages/shop/shopIndex";
            }
        }else{
            // TODO: 2021/1/11  非法操作11
            System.out.println("非法操作11，用户不能发货！");
            return "pages/shopping/shoppingIndex";
        }
    }

    @RequestMapping("/userInfo")
    public String userInfo(){ return "pages/shop/userInfo"; }

    @RequestMapping("/shopIndex")
    public String shopIndex(Model model, HttpSession session, HttpServletRequest request){
        session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        List<Good> upshelfGoods = goodService.getUpshelfGoodsByUserId(loginUser.getUserId());
        List<Good> downshelfGoods = goodService.getDownshelfGoodsByUserId(loginUser.getUserId());
        model.addAttribute("upshelfGoods",upshelfGoods);
        model.addAttribute("downshelfGoods",downshelfGoods);
        return "pages/shop/shopIndex";
    }

    @RequestMapping("/getShopOrder/{status}")
    public String getShopOrder(HttpSession session, Model model, @PathVariable("status")String status){
        User loginUser = (User) session.getAttribute("loginUser");
        if(loginUser.isRole()){
            List<Integer> goodIds = goodService.getShopAllGoodId(loginUser.getUserId());
            switch (status){
                case "refunding":
                    List<OrderInfo> refundingShopOrders = orderService.getShopOrder(loginUser.getUserId(), goodIds, "%退款中");
                    model.addAttribute("refundingShopOrders", refundingShopOrders);
                    break;
                case "sent":
                    List<OrderInfo> sentShopOrders = orderService.getShopOrder(loginUser.getUserId(), goodIds, "已发货");
                    model.addAttribute("sentShopOrders", sentShopOrders);
                    break;
                case "unsent":
                    List<OrderInfo> unsentShopOrders = orderService.getShopOrder(loginUser.getUserId(), goodIds, "待发货");
                    model.addAttribute("unsentShopOrders", unsentShopOrders);
                    break;
            }
            return "pages/shop/shopOrder/"+status;
        }else{
            System.out.println("非法操作12！买家不能操作店铺订单");
            return "forward:/shopping/shoppingIndex";
        }
    }

    //获取店铺信息
    @RequestMapping("/goShopping/{userName}")
    public String goShopping(SearchItem searchItem, Model model, @PathVariable("userName")String userName){
        //获取卖家信息
        User shopAdmin = userService.getUserByName(userName);
        //获取店铺中上架鲜花信息
        List<Good> upshelfGoods = goodService.getUpshelfGoodsByUserId(shopAdmin.getUserId());
        model.addAttribute("searchItem", searchItem);
        model.addAttribute("shopAdmin", shopAdmin);
        model.addAttribute("upshelfGoods", upshelfGoods);
        return "pages/shop/shopResult";
    }

    @RequestMapping("/addGoodPage")
    public String addGoodPage(Model model){
        model.addAttribute("good", new Good());
        return "pages/shop/addGoodPage";
    }

    //添加鲜花
    @RequestMapping("/addGood")
    public String addGood(Model model, HttpSession session, Good good, @RequestParam("img") MultipartFile file) throws IOException {
        //鲜花名和鲜花类型不能为空，鲜花进价和售价不能为空且应大于0
        if(!good.getGoodName().equals("")
                &&!good.getSpecies().equals("鲜花类型")
                &&good.getSellPrice()!=null&&good.getSellPrice()>0
                &&good.getPurchasePrice()!=null&&good.getPurchasePrice()>0){
            //若填写的鲜花库存为空或<0则设为0
            if (good.getQuantity()==null||good.getQuantity() < 0)
                good.setQuantity(0);
            User loginUser = (User) session.getAttribute("loginUser");
            good.setUserId(loginUser.getUserId());
            InputStream is = null;
            final String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\img\\tempGoodImg.jpg";
            logger.debug("\n\n"+path+"\n\n");
            //为鲜花设置图片，若未上传图片则使用临时图片
            is = file.isEmpty()?new FileInputStream(path):file.getInputStream();
            boolean flag = goodService.addGood(good, is);
            logger.debug(flag?"添加新鲜花成功":"添加新鲜花失败");
            return "forward:/shop/shopIndex";
        }else {
            model.addAttribute("good", good);
            //将错误信息传递回之前的页面
            model = goodService.setErrorInfo(model, good.getGoodName(), good.getSpecies(), good.getSellPrice(), good.getPurchasePrice());
            return "pages/shop/addGoodPage";
        }
    }
}
